package com.liwei.jms.activemq.testone;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

public class TopicPublisher {

	private Connection connection;
	private Session session;
	private MessageProducer publisher;
	private Topic topic;

	private String url = "tcp://localhost:61616";
	private int size = 256;

	private byte[] payload;

	public static void main(String[] argv) throws Exception {
		TopicPublisher p = new TopicPublisher();
		p.run();
	}

	private void run() throws Exception {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
		connection = factory.createConnection();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = session.createTopic("topictest.messages--lidian");

		publisher = session.createProducer(topic);
		// publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
		payload = new byte[size];

		connection.start();

		publish("liwei");
		publish("shenjie");
		publish("asdf");
		publish("ttttttt");

		connection.stop();
		connection.close();
	}

	private void publish(String message) throws Exception {

		// send events
		BytesMessage msg = session.createBytesMessage();
		msg.writeBytes(payload);

		// request report
		System.out.println("send:\t" + message);

		publisher.send(session.createTextMessage(message));
	}

}
